package online.keepon.document.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import online.keepon.document.common.ErrorInfo;
import online.keepon.document.common.Result;
import online.keepon.document.model.SysUser;
import online.keepon.document.model.dto.LoginDTO;
import online.keepon.document.service.SysUserService;
import online.keepon.document.util.BCryptPasswordEncoder;
import online.keepon.document.util.FileUtil;
import online.keepon.document.util.JwtTokenUtil;
import online.keepon.document.util.RsaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * @author top
 */
@RestController
@RequestMapping(value = "/api/v1/user")
public class LoginController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @PostMapping(value = "/login")
    public Result<?> login(@RequestBody @Valid LoginDTO login) throws Exception {
        SysUser sysUser = sysUserService.selectUserByName(login.getUsername());
        if (sysUser == null) {
            return Result.fail("用户不存在");
        }
        String password = RsaUtil.decrypt(login.getPassword(), RsaUtil.getPrivateKey(FileUtil.getPrivateKey()));
        boolean matches = bCryptPasswordEncoder.matches(password, sysUser.getPassword());
        if (!matches) {
            return Result.fail("密码错误");
        }
        String token = JwtTokenUtil.createAccessToken(sysUser.getUsername());
        Map<String, String> map = new HashMap<>();
        map.put("Authorization", token);
        map.put("name", sysUser.getUsername());
        map.put("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif?imageView2/1/w/80/h/80");
        return Result.ok(map);
    }

    @GetMapping(value = "/info")
    public Result<?> info(@RequestParam String token) {
        Map<String, Object> map = new HashMap<>();
        if (null != token) {
            if (JwtTokenUtil.isExpired(token)) {
                return Result.ok(ErrorInfo.VERIFY_FAILED);
            }
            DecodedJWT claims = JwtTokenUtil.parser(token);
            SysUser sysUser = sysUserService.selectUserByName(claims.getSubject());
            if (sysUser == null) {
                return Result.fail("用户不存在");
            }
            map.put("name", sysUser.getUsername());
            map.put("avatar", "https://dss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2724409193,2018760642&fm=26&gp=0.jpg");
        }
        return Result.ok(map);
    }

    @PostMapping(value = "/logout")
    public Result<?> logout() {
        return Result.ok("退出成功");
    }
}
